# -*- coding: utf-8 -*-
# @Author：fanmingxiang@touty.io
# @Date  ：2022/form_case/18 17:46
import allure
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
import time
import os
from tools.get_log import GetLog
from config import BASE_PATH
log = GetLog.get_logger()


class Base:

    def __init__(self, driver):
        self.driver = driver

    def base_find(self, loc, timeout=30, poll=0.5):
        log.info('正在查找：{}元素'.format(loc))
        wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll).until(lambda x: x.find_element(*loc))
        log.info('成功找到：{}元素'.format(loc))
        return wait

    def base_click(self, loc):
        log.info('正在对：{}元素执行点击操作'.format(loc))
        self.base_find(loc).click()

    def base_input(self, loc, value):
        el = self.base_find(loc)
        el.clear()
        log.info("正在对：{}元素执行清空操作".format(loc))
        el.send_keys(value)
        log.info("正在对：{}元素执行输入操作值为：{}".format(loc, value))

    def base_get_text(self, loc):
        el = self.base_find(loc).text
        log.info('正在对:{}元素执行获取文本操作，值为{}'.format(loc, el))
        return el

    def base_click_city(self, loc):
        self.base_click(loc)
        loc = By.CSS_SELECTOR, '//*[@text="北京市"'
        self.base_click(loc)
        loc = By.CSS_SELECTOR, '//*[@text="市辖区"'
        self.base_click(loc)
        loc = By.CSS_SELECTOR, '//*[@text="东城区"'
        self.base_click(loc)

    def base_webview(self):
        # 进入h5
        log.info('正在执行进入h5页面操作')
        self.driver.switch_to.context('WEBVIEW_com.tencent.mm:toolsmp')
        # 切换至h5
        log.info('正在执行切换至h5页面操作')
        self.driver.switch_to.window(self.driver.window_handles[0])

    def base_native(self):
        # 回到微信
        log.info('正在执行切换至APP操作')
        self.driver.switch_to.context('NATIVE_APP')

    def base_back(self):
        log.info('正在点击返回按钮')
        self.driver.press_keycode(4)

    def base_get_image(self):
        document_time_name = time.strftime("%Y-%m-%d", time.localtime(time.time()))
        picture_time_name = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time())) + '.png'
        document_path = BASE_PATH + os.sep + 'image' + os.sep + document_time_name
        if not os.path.exists(document_path):
            os.makedirs(document_path)
        picture_path = document_path + os.sep + picture_time_name
        log.info("正在执行截图操作")
        self.driver.get_screenshot_as_file(picture_path)
        self.base_write_report(picture_time_name, picture_path)

    def base_write_report(self, picture_time_name, picture_path):
        with open(picture_path, 'rb') as f:
            allure.attach(f.read(), picture_time_name, allure.attachment_type.PNG)